//
//  YsCloudFileDownloadManager+Tools.m
//  YsCloudFileManageSDK
//
//  Created by 宋宏康 on 2020/2/28.
//

#import "YsCloudFileDownloadManager+Tools.h"
#import "NSArray+QMUI.h"
#import "YsCloudFileManagerHeader.h"
#import <YYKit/YYKit.h>
#import "YsCloudRealmTool.h"

@implementation YsCloudFileDownloadManager (Tools)

- (YsCloudFileDownloadModel *)getModelFromArray:(NSArray <YsCloudFileDownloadModel *>*)modelArray
                                withdownloadUrl:(NSString *)downloadUrl{
    SemaphoreBegin;
    NSArray *fileArray =  [modelArray qmui_filterWithBlock:^BOOL(YsCloudFileDownloadModel *item) {
        return [item.requestUrl isEqualToString:downloadUrl];
    }];
    YsCloudFileDownloadModel *currentModel =  nil;
    if (fileArray.count != 0 || fileArray) {
        currentModel =  [fileArray objectOrNilAtIndex:0];
    }
    SemaphoreEnd;
    return currentModel;
}

- (void)checkDownload {
    SemaphoreBegin;
    NSInteger downloadingCount = 0;
    BOOL flag = YES;
    for (YsCloudFileDownloadModel *downloadModel in self.downloadsArray) {
        if (downloadModel.downloadStatus == 3) { /// 任务是正在下载的任务
            downloadingCount ++;
        }
        if (self.maxDownloadTaskCount == 0) { /// 外面没有设置并发数，就用默认的并发数
            self.maxDownloadTaskCount = kMAXDownloadTASK_COUNT ;
        }
        
        if (downloadingCount >= self.maxDownloadTaskCount) {
            flag = NO;
            break;
        }
    }
    NSLog(@"当前的下载数量是:%zd\n设置的最大并发数:%d",downloadingCount,self.maxDownloadTaskCount);
    
    if (flag) { // 允许下载
        /// 按照等待的时间升序
        NSArray *resultNumArray = [self.downloadsArray sortedArrayUsingComparator:^NSComparisonResult(YsCloudFileDownloadModel* obj1, YsCloudFileDownloadModel *obj2) {
            NSNumber *number1 = [NSNumber numberWithString:obj1.waitTaskTime];
            NSNumber *number2 = [NSNumber numberWithString:obj2.waitTaskTime];
            return  [number1 compare:number2]; // 升序 队列先进先出
        }];
        
        for (YsCloudFileDownloadModel *model in resultNumArray) {
            if (model.downloadStatus == 2) {// 当前的任务是等待
                if (self.maxDownloadTaskCount == 0) {
                    self.maxDownloadTaskCount = kMAXDownloadTASK_COUNT;
                }
                if (self.maxDownloadTaskCount - downloadingCount > 0) {
                    NSLog(@"开始任务了");
                    [self beginDownloadWithModel:model];
                    downloadingCount ++;
                }else {
                    break;
                }
            }
        }
    }
    SemaphoreEnd;
}

- (NSInteger)getCunrrentDownloadMaxTaskCount
{
    SemaphoreBegin;
     NSInteger downloadingCount = 0;
     BOOL flag = YES;
     for (YsCloudFileDownloadModel *downloadModel in self.downloadsArray) {
         if (downloadModel.downloadStatus == 3) { /// 任务是正在下载的任务
             downloadingCount ++;
         }
         if (self.maxDownloadTaskCount == 0) { /// 外面没有设置并发数，就用默认的并发数
             self.maxDownloadTaskCount = kMAXDownloadTASK_COUNT ;
         }
         
         if (downloadingCount >= self.maxDownloadTaskCount) {
             flag = NO;
             break;
         }
     }
     NSLog(@"当前的下载数量是:%zd\n",downloadingCount);
    SemaphoreEnd;
    return downloadingCount;
}

- (void)againOpenTask
{
    SemaphoreBegin;
    NSInteger maxTask = self.getCunrrentDownloadMaxTaskCount;
   if (maxTask == kMAXDownloadTASK_COUNT) { /// 当前下载的并发数刚好是设置的最大并发数
        /// 移除一个最后进入队列的下载任务
       NSArray *downloadingDaskArray =  [self.downloadsArray qmui_filterWithBlock:^BOOL(YsCloudFileDownloadModel *item) {
                return item.downloadStatus == 3;
       }];
       /// 按照等待的时间升序
       NSArray *resultNumArray = [downloadingDaskArray sortedArrayUsingComparator:^NSComparisonResult(YsCloudFileDownloadModel* obj1, YsCloudFileDownloadModel *obj2) {
           NSNumber *number1 = [NSNumber numberWithString:obj1.waitTaskTime];
           NSNumber *number2 = [NSNumber numberWithString:obj2.waitTaskTime];
           return  [number1 compare:number2]; // 升序 队列先进先出
       }];
     YsCloudFileDownloadModel *lastModel = [resultNumArray objectOrNilAtIndex:(resultNumArray.count - 1)];
       [self suspendWithDownloadName:lastModel.customCacheName];
    }
   [YsCloudFileDownloadManager.shareDownloadManger checkDownload];
    SemaphoreEnd;
}

- (void)checkResumeDownloadTaskWithDownloadModel:(YsCloudFileDownloadModel *)downloadModel
{
    SemaphoreBegin;
    downloadModel.waitTaskTime = [NSString stringWithFormat:@"%ld",[[YsCloudRealmTool getDownloadTaskWaitTimeWhenTaskBeginWithAccountCode:kAccountCode] integerValue] - 1];
    NSInteger maxTask = self.getCunrrentDownloadMaxTaskCount;
      if (maxTask == kMAXDownloadTASK_COUNT) { /// 当前下载的并发数刚好是设置的最大并发数
           /// 移除一个最后进入队列的下载任务
          NSArray *downloadingDaskArray =  [self.downloadsArray qmui_filterWithBlock:^BOOL(YsCloudFileDownloadModel *item) {
                   return item.downloadStatus == 3;
          }];
          /// 按照等待的时间升序
          NSArray *resultNumArray = [downloadingDaskArray sortedArrayUsingComparator:^NSComparisonResult(YsCloudFileDownloadModel* obj1, YsCloudFileDownloadModel *obj2) {
              NSNumber *number1 = [NSNumber numberWithString:obj1.waitTaskTime];
              NSNumber *number2 = [NSNumber numberWithString:obj2.waitTaskTime];
              return  [number1 compare:number2]; // 升序 队列先进先出
          }];
        YsCloudFileDownloadModel *lastModel = [resultNumArray objectOrNilAtIndex:(resultNumArray.count - 1)];
          [self suspendWithDownloadName:lastModel.customCacheName];
       }
    [YsCloudFileDownloadManager.shareDownloadManger resumeWithdownloadName:downloadModel.customCacheName];
    SemaphoreEnd;
}
@end
